<template>
  <GroupPage :has-content-title="false" class="p-0" @search="searchFn">
    <template #group>
      <SpinSkeleton v-show="grpData.length > 0" :loading="grpLoading">
        <div v-if="!isEnterprise" class="flex flex-row flex-wrap items-center lg:block lg:flex-nowrap">
          <div
            v-for="(el, i) in grpData"
            :key="el.equipmentParamGroupsId"
            class="py-2 px-4 mb-2 cursor-pointer mr-2 lg:mr-0 relative show-edit"
            :class="[curIndex === i ? 'bg-opacity-10 bg-color-active' : 'bg-header']"
            @click="handleCheckModal(el, i)"
          >
            <div class="mb-1" :class="[curIndex === i ? 'text-color-active' : 'text-color-main']">
              {{ el.equipmentParamGroupsName }}
            </div>
            <div
              :title="el.remark"
              class="text-color-secondary text-sm overflow-hidden text-ellipsis whitespace-nowrap"
              >{{ el.remark }}</div
            >
            <div
              v-if="!(['key_param', 'control_param', 'operation_param','event_param'].includes((el.equipmentParamGroupsCode as string)) || el.equipmentParamGroupsId === '')"
              class="absolute right-2 transform top-1/3 hidden edit-block"
            >
              <Icon
                v-show="!isEnterprise"
                type="icon-shanchu"
                class="text-color-danger"
                @click="setFunctionGroupShowOptions({ action: CURDAction.DELETE, record: el })"
              />
              <Icon
                v-show="!isEnterprise"
                type="icon-bianji"
                class="text-color-active ml-2"
                @click="setFunctionGroupShowOptions({ action: CURDAction.UPDATE, record: el })"
              />
            </div>
          </div>
        </div>
        <div v-else>
          <a-tree
            v-model:selectedKeys="selectedKeys"
            show-icon
            block-node
            :tree-data="(grpData as any)"
            :field-names="{
              title: 'equipmentParamGroupsName',
              key: 'equipmentParamGroupsId',
            }"
            @select="handleSelectTreeNode"
          >
            <template #icon="{ parentId }">
              <Icon v-show="parentId === '0'" type="icon-xilie" class="text-2xl mr-4" />
            </template>
            <template #title="el">
              <div class="w-full flex flex-row items-center icon-row">
                <EllipsisText :max-len="10" :text="el.equipmentParamGroupsName" />
                <a-button
                  v-if="el.parentId === '0' && !isView"
                  type="link"
                  class="icon-btn absolute right-0"
                  @click.stop="handleAddChild(el.equipmentParamGroupsId)"
                >
                  <Icon type="icon-tianjia" /> 添加子组</a-button
                >
                <Icon
                  v-if="el.parentId !== '0'"
                  type="icon-bianji"
                  class="icon-btn text-xl absolute text-color-active right-12"
                  @click.stop="editGrpFn(el)"
                />
                <Icon
                  v-if="el.parentId !== '0'"
                  type="icon-shanchu"
                  class="icon-btn text-xl text-color-danger absolute right-4"
                  @click="setFunctionGroupShowOptions({ action: CURDAction.DELETE, record: el })"
                />
              </div>
            </template>
          </a-tree>
        </div>
      </SpinSkeleton>
      <!-- 暂时去掉 -->
      <!-- <PermissionBtn
        v-show="!isEnterprise"
        class="absolute bottom-0 w-4/5"
        :oper-type="OperPermissionType.MANAGE"
        :disabled="!curSelectedGroup"
        :btn-props="{ block: true }"
        @click="handleAddGroup"
      >
        新增分组
        <template #icon>
          <Icon type="icon-tianjia" class="" />
        </template>
      </PermissionBtn> -->
      <SlEmpty v-show="!grpLoading && grpData.length === 0" :description="emptyText"></SlEmpty>
    </template>
    <template #content>
      <div class="pl-7 pt-7 pr-2.5">
        <SearchForm
          ref="searchIns"
          :keyword-search-data="[{ label: '点位/参数名称', key: 'searchText' }]"
          :show-add-btn="false"
          @search="searchFn"
        >
          <template #extraButtons>
            <PermissionBtn
              v-show="!isView"
              class="mr-4.5"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ danger: true, disabled: !(curSelectedGroup && selectedFunctionKeys.length > 0) }"
              @click="
                setShowOptions({
                  action: CURDAction.DELETE,
                  ids: selectedFunctionKeys,
                  message: '您确定要删除已选点位吗？',
                })
              "
            >
              删除点位
              <template #icon>
                <Icon type="icon-shanchu" />
              </template>
            </PermissionBtn>
            <PermissionBtn
              v-show="!isView"
              class="mr-4.5"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ type: 'primary' }"
              @click="addFunc"
            >
              新增点位
              <template #icon>
                <Icon type="icon-tianjia" class="" />
              </template>
            </PermissionBtn>
            <PermissionBtn
              v-show="!isView"
              class="mr-4.5"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ type: 'primary' }"
              @click="downloadFn"
            >
              下载模板
            </PermissionBtn>
            <PermissionBtn
              v-show="!isView"
              class="mr-4.5"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ type: 'primary', disabled: !(tableData && tableData.length > 0) }"
              :disabled-mes="tableData && tableData.length > 0 ? null : '暂无导出数据'"
              @click="exportFileFn"
            >
              导出Excel
            </PermissionBtn>
            <!-- <PermissionBtn
              v-show="!isView"
              class="mr-4.5"
              :oper-type="OperPermissionType.MANAGE"
              :btn-props="{ type: 'primary' }"
              @click="downloadFn"
            >
              导入Excel
            </PermissionBtn> -->
            <a-upload v-show="!isView" accept=".xls,.xlsx" :show-upload-list="false" :custom-request="customRequest">
              <a-button type="primary">导入Excel</a-button>
            </a-upload>
          </template>
        </SearchForm>
      </div>
      <div class="flex-1 overflow-hidden px-7 pb-7">
        <SlTable
          :columns="columns"
          :row-key="isEnterprise ? 'equipmentTypeAttributeId' : 'defaultEquipmentTypeAttributeId'"
          :data-source="tableData"
          :loading="tableLoading"
          :scroll="{ x: true }"
          :row-selection="rowSelection"
          :search-model="searchModel"
          :ignore-keys="['groupCode', 'equipmentTypeId', 'equipmentParamGroupsIdList']"
        >
          <template #bodyCell="{ column, record, index }">
            <a-space v-if="column.key === 'oper'">
              <PermissionBtn
                v-show="props.isEnterprise"
                :btn-props="{ type: 'link' }"
                :oper-type="OperPermissionType.MANAGE"
                @click="handleSetKeyAttr(record)"
              >
                {{ record.keyAttribute ? "取消星标" : "设为星标" }}
              </PermissionBtn>
              <PermissionBtn
                v-show="!isView"
                :btn-props="{ type: 'link' }"
                :oper-type="OperPermissionType.MANAGE"
                @click="handleEdit(record)"
              >
                编辑
              </PermissionBtn>
              <PermissionBtn
                v-show="!isView"
                :btn-props="{ type: 'link', danger: true }"
                :oper-type="OperPermissionType.MANAGE"
                class="text-red-400"
                @click="setShowOptions({ action: CURDAction.DELETE, record })"
              >
                删除
              </PermissionBtn>
            </a-space>
            <div v-if="column.dataIndex === 'attributeName'" class="flex flex-row items-center">
              <div class="pr-4 pb-1" style="font-size: 0" @mousedown="sortStart($event, index)">
                <Icon type="icon-tuodong" class="text-2xl cursor-move !text-color-secondary" />
              </div>
              <EllipsisText
                class="text-color-active cursor-pointer"
                :max-len="20"
                :text="record.attributeName"
                @click="handleView(record, index)"
              />
              <Icon v-show="record.keyAttribute" type="icon-wujiaoxing-2" class="!text-color-warn ml-2" />
            </div>
            <p v-if="column.dataIndex === 'dataType'" class="m-0 w-20">{{ dataType[record.dataType] || "--" }}</p>
            <p v-if="column.dataIndex === 'attributeLevel'" class="m-0 w-20">{{
              AttributeLevel[record.attributeLevel] || "--"
            }}</p>
            <p v-if="column.dataIndex === 'readWriteType'" class="m-0 w-20">{{
              ReadWriteType[record.readWriteType] || "--"
            }}</p>
            <p v-if="column.dataIndex === 'functionType'" class="m-0 w-20">{{
              FunctionType[record.functionType] || "--"
            }}</p>
            <div v-if="column.dataIndex === 'display'">
              <a-switch
                v-model:checked="record.display"
                checked-children="开"
                un-checked-children="关"
                @change="handleChangeActiveFn(record)"
              />
            </div>
            <EllipsisText
              v-if="column.dataIndex === 'attributeDesc'"
              :width="100"
              :max-len="25"
              :text="record.attributeDesc"
            />
            <EllipsisText
              v-if="column.dataIndex === 'attributeDisplayName'"
              :width="120"
              :max-len="25"
              :text="record.attributeDisplayName"
            />
          </template>
        </SlTable>
      </div>
    </template>
    <CURDDialog
      ref="grpIns"
      :create-title="currentParentId ? '新增功能分组子组' : '新增功能分组'"
      update-title="编辑功能分组"
      delete-message="您确定要删除该功能分组"
      :show-options="grpShowOptions"
      :columns="grpColumns"
      :model="grpModel"
      :model-form-setting="gropModelFormSetting"
      :table-data="grpData"
      :curd="grpCurd"
      id-key="equipmentParamGroupsId"
      :reload-table="grpReloadTable"
      drawer-container-selector="#app"
      @before-ok="groupBeforeOk"
    />

    <CURDDialog
      ref="functionIns"
      v-model:model-form-setting="modelFormSetting"
      create-title="新增功能"
      update-title="编辑点位"
      delete-message="您确定要删除该功能吗？"
      :show-options="showOptions"
      :columns="(columns as any)"
      :model="model"
      :table-data="tableData"
      :curd="curd"
      :id-key="isEnterprise ? 'equipmentTypeAttributeId' : 'defaultEquipmentTypeAttributeId'"
      :reload-table="reloadTable"
      :get-delete-params="getUserDeleteParams"
      @before-ok="beforeOk"
      @ok="reloadTable"
    />
  </GroupPage>
  <AddEquipmentAttrModal
    v-model:visible="addEquipmentAttrVisible"
    v-model:equipment-attr="curEquipmentAttr"
    :options="groupOption"
    :is-enterprise="isEnterprise"
    drawer-container-selector="#root"
    :pre-disabled="preDisabled"
    :next-disabled="nextDisabled"
    @done="reloadTable"
    @handle-pre-or-next="handlePreOrNextEdit"
  />
  <EquipmentFunctionView
    v-model:id="currentEquipmentAttrId"
    :is-enterprise="isEnterprise"
    :pre-disabled="preDisabled"
    :next-disabled="nextDisabled"
    @handle-pre-or-next="handlePreOrNext"
  />
</template>

<script lang="ts" setup>
import { nextTick, reactive, ref, shallowRef, watch, computed, onMounted, provide } from "vue";
import FullPageModal from "/@/components/FullPageModal.vue";
import {
  CURDAction,
  CURDModalEvent,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
} from "/@/components/CURDDialog/models";
import { OperPermissionType } from "/@/api/aiot/role/models";
import { message } from "ant-design-vue";
import {
  EquipmentAttrItem,
  ParEquipmentAttrItem,
  ParEquipmentTypeGroup,
  ReadWriteType,
  FunctionType,
  GroupOptions,
  AttributeLevel,
} from "/@/api/aiot/equipmentType/models";
import { useCURD } from "/@/hooks/useCURD";
import { useEmptyText } from "/@/hooks/useEmptyText";
import { PatternKey } from "/@/utils/verify";
import { useRowDragSort } from "/@/hooks/useRowDragSort";
import { useSetEquipmentFunction } from "./useSetEquipmentFunction";
import { EquipmentFunctionModalOptions } from "/@/api/aiot/equipment/models";
import { getDictionaryByType } from "/@/api/aiot/dictionary";
import { SearchFormKeywordKey } from "/@/types/components";
import {
  attrUpdateSys,
  attrUpdate,
  changeEquipmentTypeAttributesStatus,
  importAttr,
  exportAttr,
  updateDisplayOrder,
  exportTemp,
} from "/@/api/aiot/equipmentType";
import { loopItem } from "/@/utils/treeData";
import { OrderRule } from "/@/api/models";
import type { UploadProps } from "ant-design-vue";
import type { UploadRequestError } from "ant-design-vue/es/vc-upload/interface";
import { downloadFile } from "/@/utils/common";

const props = withDefaults(
  defineProps<{
    visible: boolean;
    activeTab: "view" | "temp";
    isEnterprise: boolean;
    options: EquipmentFunctionModalOptions;
    isView?: boolean;
  }>(),
  {
    isView: false,
  }
);
const groupOption = ref<GroupOptions>({
  equipmentParamGroupsId: "",
  groupCode: "",
  equipmentTypeId: props.options.equipmentTypeId,
});
const { Api } = useSetEquipmentFunction(props.isEnterprise);
const emits = defineEmits(["create", "update:visible", "successFn"]);

const addEquipmentAttrVisible = ref<boolean>(false);
const preDisabled = ref<boolean>(true);
const nextDisabled = ref<boolean>(false);
const grpShowOptions = shallowRef<ShowCURDModalOptions>();
const curSelectedGroup = ref<ParEquipmentTypeGroup>({});
const curIndex = ref(-1);
const grpIns = ref();
const keyword = ref<string>("");
const currentEquipmentAttrId = ref<string>("");
const functionIns = ref();
const curEquipmentAttr = ref<ParEquipmentAttrItem>({});
const curGroupCode = ref<string>("");
const curEquipmentParamGroupsId = ref<string>("");
const equipmentParamGroupsId = ref<string>("");
const equipmentParamGroupsIdList = ref<string[]>([]);
const { emptyText } = useEmptyText();
const selectedKeys = ref<string[]>([]);
const curViewIndex = ref<number>(0); // 当前查看详情的index
const columns = ref([
  {
    title: "点位名称",
    dataIndex: "attributeName",
    width: 200,
  },
  // {
  //   title: "排序值",
  //   dataIndex: "equipmentTypeAttributeId",
  // },
  {
    title: "参数名称(显示名称)",
    dataIndex: "attributeDisplayName",
    width: 200,
  },
  {
    title: "参数分组",
    dataIndex: "equipmentParamGroupsName",
    width: 200,
  },
  {
    title: "参数级别",
    dataIndex: "attributeLevel",
    width: 200,
  },
  {
    title: "是否显示",
    dataIndex: "display",
    width: 200,
  },
  {
    title: "读写类型",
    dataIndex: "readWriteType",
    width: 200,
  },
  {
    title: "数据类型",
    dataIndex: "dataType",
    width: 200,
  },
  {
    title: "值状态说明",
    dataIndex: "attributeDesc",
    width: 200,
  },
  {
    title: "操作",
    key: "oper",
    width: 100,
    fixed: "right",
  },
]);

const {
  curd: grpCurd,
  tableData: grpData,
  tableLoading: grpLoading,
  reloadTable: grpReloadTable,
} = useCURD<ParEquipmentTypeGroup>({
  getPageUrl: Api.equipmentGroupPage,
  createUrl: Api.addEquipmentParamGroups,
  updateUrl: Api.updateEquipmentParamGroups,
  deleteUrl: Api.deleteByIds,
  loadOnMounted: false,
  onLoadSuccess(data) {
    loopItem(data, (el, i, items) => {
      if (!el.children || el.children.length === 0) {
        delete el.children;
      }
    });
  },
});
const { curd, tableData, tableLoading, reloadTable, searchModel } = useCURD<ParEquipmentAttrItem>({
  getPageUrl: Api.attrPage,
  createUrl: Api.attrAdd,
  updateUrl: Api.attrUpdate,
  deleteUrl: Api.attrDel,
  loadOnMounted: false,
  pageSize: 999,
  onLoadSuccess(data) {
    // data.forEach((el) => {
    //   console.log(el.attributeName, el.displayOrder);
    // });
  },
});
const { sortStart } = useRowDragSort({
  adjustNow: true,
  async onSort(curRecord, targetRecord, isUp, curIndex, targetIndex) {
    // console.info(curRecord, targetRecord, isUp, curIndex, targetIndex);
    // console.info("targetRecord", targetRecord);
    // console.info("attributeName", targetRecord.attributeName);
    // console.info("====>curRecord", curRecord.attributeName);
    // console.info("curIndex", curIndex);
    // console.info("targetIndex", targetIndex);
    const idKey = props.isEnterprise ? "equipmentTypeAttributeId" : "defaultEquipmentTypeAttributeId";
    let req = await updateDisplayOrder(
      {
        dragPosition: isUp ? "UP" : "DOWN",
        displayOrder: targetRecord.displayOrder as number,
        [idKey]: curRecord[idKey] as string,
      },
      !props.isEnterprise
    );
    req && reloadTable();
  },
  data: tableData,
  rowKey: "equipmentTypeAttributeId",
});
const showOptions = ref<ShowCURDModalOptions>();
function setShowOptions(options: ShowCURDModalOptions) {
  showOptions.value = options;
}

const groupCode = computed(() => {
  return grpData.value[curIndex.value]?.equipmentParamGroupsCode || curGroupCode.value;
});
watch(
  () => curIndex.value,
  (v) => {
    if (v >= 0) {
      reloadTable({
        model: {
          // groupCode: grpData.value[curIndex.value]?.equipmentParamGroupsCode || "",
          equipmentParamGroupsId: grpData.value[curIndex.value]?.equipmentParamGroupsId || "",
          equipmentTypeId: props.options.equipmentTypeId,
          searchText: "",
        },
      });
    }
  }
);

watch(
  () => props.activeTab,
  async (v) => {
    if (v === "temp") {
      await grpReloadTable({ model: { equipmentTypeId: props.options.equipmentTypeId }, size: 999, current: 1 });
      // curIndex.value = 0;
      reloadTable({ model: { groupCode: "", equipmentTypeId: props.options.equipmentTypeId } });
      // selectedKeys.value = [grpData.value[0].equipmentParamGroupsId || ""];
    } else {
      selectedFunctionKeys.value = [];
    }
  }
);
watch(
  () => props.options,
  (v) => {
    console.info("v===>", v);
  }
);
const dataType = ref({});
onMounted(async () => {
  // 初始化请求数据
  await grpReloadTable({ model: { equipmentTypeId: props.options.equipmentTypeId }, size: 999, current: 1 });
  reloadTable({
    model: { groupCode: "", equipmentTypeId: props.options.equipmentTypeId },
    sort: "displayOrder",
    order: OrderRule.DESC,
  });
  // 清空已选择的功能
  selectedFunctionKeys.value = [];
  dataType.value = {};
  let data = (await getDictionaryByType({ dictionaryType: "DATATYPE" })) || [];
  if (data && data.length > 0) {
    data.forEach((item) => {
      dataType.value[item.dictionaryCode] = item.dictionaryName;
    });
  }
});
let selectedFunctionKeys = ref<string[]>([]);
const rowSelection = {
  onChange: (selectedRowKeys: string[], selectedRows: ParEquipmentAttrItem[]) => {
    selectedFunctionKeys.value = selectedRowKeys;
  },
  getCheckboxProps: (record: ParEquipmentAttrItem) => ({}),
};
async function handleSetKeyAttr(record: EquipmentAttrItem) {
  let obj: ParEquipmentAttrItem = {
    equipmentTypeAttributeId: record.equipmentTypeAttributeId,
    keyAttribute: !record.keyAttribute,
  };
  let req = await changeEquipmentTypeAttributesStatus(obj);
  if (req) {
    reloadTable();
  }
}
function reset() {}
function searchFn({ searchText }) {
  reloadTable({ model: { searchText } });
}
function setFunctionGroupShowOptions(options: ShowCURDModalOptions) {
  grpShowOptions.value = options;
}
/**
 * ok cancel
 */
async function ok(isContinue) {}
function handleCheckModal(el, i) {
  keyword.value = "";
  curIndex.value = i;
  curGroupCode.value = el.equipmentParamGroupsCode;
  equipmentParamGroupsId.value = el.equipmentParamGroupsId;

  grpIns.value?.isOpen() && setFunctionGroupShowOptions({ action: CURDAction.UPDATE, record: el });
}

provide(SearchFormKeywordKey, keyword);
// 自定义删除用户方法
const getUserDeleteParams = (id) => {
  return id ? [id] : selectedFunctionKeys.value;
};
function beforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as ParEquipmentAttrItem;
    if (e.action === CURDAction.CREATE) {
      e.model.groupCode = curGroupCode.value || "";
    }
  }
}
function groupBeforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as ParEquipmentTypeGroup;
    if (e.action === CURDAction.CREATE) {
      console.info("新增");
      e.model.equipmentTypeId = props.options.equipmentTypeId;
      // 如果currentParentId 为空则不赋值
      if (currentParentId.value) {
        e.model.parentId = currentParentId.value;
      }
    }
    console.info("e====>", e.model);
  }
}
const currentParentId = ref<string>();
function handleAddChild(id) {
  console.info("id", id);
  currentParentId.value = id;
  setFunctionGroupShowOptions({ action: CURDAction.CREATE });
}
const model = ref<ParEquipmentAttrItem>({
  functionType: "",
  attributeName: "",
  attributeId: "",
  readWriteType: "",
  dataType: "",
  equipmentTypeAttributeId: "",
});
var modelFormSetting: FormItemData[] = [
  {
    key: "attributeName",
    label: "点位名称 ",
    required: true,
    max: 32,
  },
  {
    key: "attributeDisplayName",
    label: "参数名称(显示名称)",
    required: true,
    labelDes: "若不填写，系统自动默认为点位名称",
    max: 32,
  },
  {
    key: "equipmentParamGroupsId",
    label: "参数分组 ",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData() {
      return grpData.value;
      // let data = await getDictionaryByType({ dictionaryType: "DATATYPE" });
      // return data
      //   ? data.map((el) => ({
      //       label: el.dictionaryName,
      //       value: el.dictionaryCode,
      //     }))
      //   : [];
    },
    props: {
      fieldNames: { label: "equipmentParamGroupsName", value: "equipmentParamGroupsId" },
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "attributeLevel",
    label: "功能级别 ",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "重要", value: "import" },
        { label: "次要", value: "minor" },
        { label: "一般", value: "general" },
      ],
    },
  },
  {
    key: "display",
    label: "是否显示 ",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "显示", value: "true" },
        { label: "不显示", value: "false" },
      ],
    },
  },
  {
    key: "readWriteType",
    label: "读写类型 ",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "只读", value: "R" },
        { label: "读写", value: "RW" },
      ],
    },
  },
  //   string
  // float
  // int
  // boolean
  {
    key: "dataType",
    label: "数据类型 ",
    type: FormItemComponentType.SELECT,
    required: true,
    async getData() {
      let data = await getDictionaryByType({ dictionaryType: "DATATYPE" });
      return data
        ? data.map((el) => ({
            label: el.dictionaryName,
            value: el.dictionaryCode,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "equipmentTypeAttributeId",
    hide: true,
  },
];
const grpColumns = ref([
  {
    title: "功能分组名称",
    dataIndex: "equipmentParamGroupsName",
    width: 100,
  },
  {
    title: "分组唯一标识",
    dataIndex: "equipmentParamGroupsCode",
    width: 100,
  },
  {
    title: "功能分组备注",
    dataIndex: "remark",
    width: 100,
  },
]);
const grpModel = ref<ParEquipmentTypeGroup>({
  equipmentParamGroupsName: "",
  equipmentParamGroupsCode: "",
  remark: "",
});
const gropModelFormSetting: FormItemData[] = [
  {
    key: "equipmentParamGroupsName",
    label: "分组名称",
    max: 32,
    required: true,
  },
  {
    key: "equipmentParamGroupsCode",
    label: "分组唯一标识",
    max: 32,
    required: true,
    labelDes: "支持大小写字母、数字和下划线",
    pattern: PatternKey.code,
    // pattern: PatternKey.name,
  },
  {
    key: "remark",
    label: "备注",
    max: 250,
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "equipmentParamGroupsId",
    hide: true,
  },
];

function handleEdit(record) {
  console.info("record", record);
  curEquipmentAttr.value = record;
  addEquipmentAttrVisible.value = true;
}
function addFunc() {
  groupOption.value = {
    equipmentParamGroupsId: equipmentParamGroupsId.value,
    groupCode: curGroupCode.value,
    equipmentTypeId: props.options.equipmentTypeId,
  };
  curEquipmentAttr.value = {};
  addEquipmentAttrVisible.value = true;
}
function handleView(record: EquipmentAttrItem, curIndex) {
  currentEquipmentAttrId.value = record.equipmentTypeAttributeId || record.defaultEquipmentTypeAttributeId;
  curViewIndex.value = curIndex;
  curIndex > 0 ? (preDisabled.value = false) : (preDisabled.value = true);
  curIndex >= tableData.value.length - 1 ? (nextDisabled.value = true) : (nextDisabled.value = false);
}
function handleSelectTreeNode(equipmentCategoryId, node) {
  // 保存当前选择的功能粉分组code
  keyword.value = "";
  curGroupCode.value = node.node.equipmentParamGroupsCode;
  curEquipmentParamGroupsId.value = node.node.equipmentParamGroupsId;
  equipmentParamGroupsId.value = node.node.equipmentParamGroupsId;
  equipmentParamGroupsIdList.value = [];
  let data: EquipmentAttrItem[] = [node.node];
  loopItem(data, (el, i, item) => {
    if (el.equipmentParamGroupsId) {
      equipmentParamGroupsIdList.value.push(el.equipmentParamGroupsId);
    }
  });
  reloadTable({
    model: {
      // groupCode: node.node?.equipmentParamGroupsCode || "",
      // equipmentParamGroupsId: node.node?.equipmentParamGroupsId || "",
      equipmentParamGroupsIdList: equipmentParamGroupsIdList.value,
      equipmentTypeId: props.options.equipmentTypeId,
      searchText: "",
    },
  });
}
function handleAddGroup() {
  currentParentId.value = "";
  setFunctionGroupShowOptions({ action: CURDAction.CREATE });
}
async function downloadFn() {
  exportTemp({ useDefaultFailHandle: false })
    .then((res) => {
      res && downloadFile(res, "点表模板" + ".xls");
    })
    .catch((err) => {
      // 进失败回调，因为没有返回status 200
      err && downloadFile(err, "点表模板" + ".xls");
    });
}
// 导入
const importing = ref(false);
const customRequest: UploadProps["customRequest"] = async (options) => {
  if (!props.options) return;
  let formData = new FormData();
  formData.append("file", options.file);
  formData.append("equipmentTypeId", props.options.equipmentTypeId);
  importing.value = true;
  let req = await importAttr(formData, props.options.equipmentTypeId);
  importing.value = false;
  if (req) {
    options.onSuccess &&
      options.onSuccess({
        status: "done",
      });
    message.success("操作成功");
    reloadTable();
  } else {
    let obj: UploadRequestError = {
      status: 500,
      name: "",
      message: "上传失败",
    };
    options.onError && options.onError(obj);
  }
};
// 是否显示操作
async function handleChangeActiveFn(row: ParEquipmentAttrItem) {
  let req: boolean | null = false;
  if (props.isEnterprise) {
    let obj = {
      display: row.display,
      equipmentTypeAttributeId: row.equipmentTypeAttributeId,
    };
    req = await attrUpdate(obj);
  } else {
    let obj = {
      display: row.display,
      defaultEquipmentTypeAttributeId: row.defaultEquipmentTypeAttributeId,
    };
    req = await attrUpdateSys(obj);
  }
  reloadTable();
  if (req) {
    message.success("操作成功");
  }
}
function handlePreOrNextEdit(type) {
  let len = tableData.value?.length;
  if (type === 1) {
    curViewIndex.value < len ? curViewIndex.value++ : null;
    curViewIndex.value === len - 1 ? (nextDisabled.value = true) : (nextDisabled.value = false);
    if (curViewIndex.value < len) {
      let record = tableData.value[curViewIndex.value];
      curEquipmentAttr.value = record;
      preDisabled.value = false;
    }
  } else {
    curViewIndex.value > 0 ? curViewIndex.value-- : null;
    curViewIndex.value === 0 ? (preDisabled.value = true) : (preDisabled.value = false);
    if (curViewIndex.value >= 0) {
      nextDisabled.value = false;
      let record = tableData.value[curViewIndex.value];
      curEquipmentAttr.value = record;
    }
  }
}
function handlePreOrNext(type) {
  // type 1下一步  0上一步
  let len = tableData.value?.length;
  if (type === 1) {
    curViewIndex.value < len ? curViewIndex.value++ : null;
    curViewIndex.value === len - 1 ? (nextDisabled.value = true) : (nextDisabled.value = false);
    if (curViewIndex.value < len) {
      let record = tableData.value[curViewIndex.value];
      currentEquipmentAttrId.value = record.equipmentTypeAttributeId || record.defaultEquipmentTypeAttributeId || "";
      preDisabled.value = false;
    }
  } else {
    curViewIndex.value > 0 ? curViewIndex.value-- : null;
    curViewIndex.value === 0 ? (preDisabled.value = true) : (preDisabled.value = false);
    if (curViewIndex.value >= 0) {
      nextDisabled.value = false;
      let record = tableData.value[curViewIndex.value];
      currentEquipmentAttrId.value = record.equipmentTypeAttributeId || record.defaultEquipmentTypeAttributeId || "";
    }
  }
}
async function exportFileFn() {
  // let req: Blob = await exportAttr(props.options.equipmentTypeId, { useDefaultFailHandle: false });
  exportAttr(props.options.equipmentTypeId, { useDefaultFailHandle: false })
    .then((res) => {
      res && downloadFile(res, props.options.equipmentTypeName + ".xls");
    })
    .catch((err) => {
      // 进失败回调，因为没有返回status 200
      err && downloadFile(err, props.options.equipmentTypeName + ".xls");
    });
}
function editGrpFn(record) {
  setFunctionGroupShowOptions({ action: CURDAction.UPDATE, record });
}
</script>
<style lang="less" scoped>
.show-edit:hover {
  .edit-block {
    display: block !important;
  }
}
:deep(.ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected) {
  background-color: rgba(66, 133, 244, 0.1);
}
:deep(.ant-tree.ant-tree-block-node .ant-tree-list-holder-inner .ant-tree-node-content-wrapper) {
  height: 44px;
  display: flex;
  align-items: center;
  width: 100%;
}
:deep(.ant-tree .ant-tree-node-content-wrapper .ant-tree-iconEle) {
  padding-top: 2px;
}
:deep(.ant-tree-switcher) {
  display: flex;
  flex-direction: row;
  align-items: center;
}
:deep(.ant-tree-title) {
  width: 100%;
}
.icon-row:hover {
  width: 100%;
  .icon-btn {
    display: block !important;
  }
}
.icon-btn {
  display: none;
}
:deep(.mb-2:has(.tab-content)) {
  width: 100%;
}
</style>
<style lang="less">
.setfunction-container {
  .ant-modal-body {
    padding: 0;
  }
}
</style>
